"""
 encoding    : utf-8
 @File       : tools.py
 @Author     : Rao
 @Version    : 3.0
 @Description: OA系统测试工具类, 3.0版本增加获取yaml文件位置的功能
 @Date       : 2024/06/06
"""
import time
import os

import yaml

from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from pathlib import Path


class QueryFile:
    """初始化类
        功能：读取yaml配置文件,将获取到的数据传递给工具类
    """

    @staticmethod
    def find_path(file_name='data.yaml', start_dir=None):
        """
        查找任意文件的路径, 默认是data.yaml, 可以选择自己需要的文件

        :start_dir: 开始搜索的目录，默认为None，表示从当前目录开始搜索。
        :return: 返回找到的data.yaml文件的Path对象，如果没有找到则返回None。
        """
        if start_dir is None:
            start_dir = Path.cwd()  # 当前工作目录
        else:
            start_dir = Path(start_dir).resolve()

        # 搜索文件, 返回文件的绝对路径
        for path in start_dir.rglob(f'{file_name}'):
            return path.resolve()  # 返回完整路径
        return None  # 如果没有找到文件，返回None

    @staticmethod
    def yaml_data(fpath):
        """读取yaml文件并返回获取的内容"""
        with open(rf'{fpath}', 'r', encoding='utf-8') as f:
            fdata = yaml.safe_load(f)
            # 测试数据
            # datalist = fdata['data']
            # print(datalist['username'], datalist['password'])
            # print(fdata['data']['username'])
            # path = fdata['url']
            # print(path)
            return fdata


class Tools:
    """工具类"""

    def __init__(self):
        """初始化变量
            从Init类获取到配置文件内的用户名、密码、路径
            创建webdriver实例
            定义隐式等待时间为10
        """
        self.parent_element = None
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(10)  # 隐式等待时间

    def login(self, data):
        """登录功能
            1. 打开网页
            2. 输入用户名和密码
            3. 关闭提示信息
        """
        # 给变量赋值
        datalist = data['data']
        username = datalist['username']
        pwd = datalist['password']
        path = data['url']

        # 打开网页
        driver = self.driver
        driver.get(path)

        # 输入用户名
        driver.find_element(By.NAME, "loginId").send_keys(username)
        # 密码
        driver.find_element(By.NAME, "password").send_keys(pwd)
        actions = ActionChains(driver)
        actions.send_keys(Keys.ENTER).perform()

        # time.sleep(2)
        # # 等待提示信息出现并关闭
        # driver.find_element(By.XPATH, '//*[@id="msg_close"]').click()
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.XPATH, '//*[@id="msg_close"]'))
        ).click()

    def select(self, option, value):
        """选择测试模块:
            1. 协同办公
            2. 公共信息
            3. 文档管理
            4. 电子邮件
            5. 工作记录
        """
        driver = self.driver
        # 查询到左侧菜单
        self.parent_element = driver.find_element(By.XPATH, '//div[@id="leftmenuDiv"]')
        try:
            if option > 5 | option < 0:
                raise ValueError("值错误")
        except ValueError as e:
            print(e)
        path = f'//h3[{option}]'
        ele = self.parent_element.find_element(By.XPATH, path)
        ele.click()
        self.check_item(option, value)

    def check_item(self, option, value):
        """选择不同测试模块里的内容"""
        num = 2 + (value - 1) * 3
        # 路径字典,这里用的是Xpath方法的路径
        path = f'div[{option}]//tr[{num}]//a'
        self.parent_element.find_element(By.XPATH, path).click()


class PreStep:
    def __init__(self):
        self.driver = None

    def pre_step(self, option, value):
        """杨家红的建议, 调用一个方法实现登录、选择自己所需模块的操作"""
        # 登录操作
        tools = Tools()
        self.driver = tools.driver
        file_path = QueryFile.find_path()
        tools.login(QueryFile.yaml_data(file_path))

        # 选择自己所属模块
        tools.select(option, value)


if __name__ == '__main__':
    ypath = QueryFile.find_path()
    QueryFile.yaml_data(ypath)
    # tools = Tools()
    # tools.login(QueryFile.yaml_data(ypath))
